<script setup>
import { Edit, Delete } from '@element-plus/icons-vue'
import { onMounted, ref } from 'vue'
import { getUserGoodsService, addUserGoodsService, updateGoodsService, deleteGoodsService } from '@/apis/goods'
import { getSubCategoryListService } from '@/apis/category'
import { ElMessage, ElMessageBox } from 'element-plus'

//用户搜索时选中的分类id
const categoryId = ref('')

//用户搜索时选中的发布状态
const status = ref('')

const categorys = ref([])
const getCategory = async () => {
    const res = await getSubCategoryListService()
    categorys.value = res.data
}

const goodsList = ref([])
//分页条数据模型
const page = ref(1)//当前页
const total = ref(0)//总条数
const pageSize = ref(5)//每页条数

const getGoodsList = async () => {
    const params = {
        page: page.value,
        pageSize: pageSize.value,
        categoryId: categoryId.value ? categoryId.value : null,
        status: status.value ? status.value : null
    }
    const res = await getUserGoodsService(params)
    goodsList.value = res.data.items
    total.value = res.data.total
}
onMounted(() => { getCategory(), getGoodsList() })

// 创建格式化函数
const formatStatus = ({ status }) => {
    const statusMap = {
        0: '禁用',
        1: '启用',
    }
    return statusMap[status]
}

// 页数切换
const pageChange = (newPage) => {
    page.value = newPage
    getGoodsList()
}

//控制抽屉是否显示
const visibleDrawer = ref(false)
//添加商品数据模型
const goods = ref({
    name: '',
    categoryId: '',
    desc: '',
    price: '',
    picture: '',
    pictures: [],
    status: '0'
})

// 添加商品
const addGoods = async () => {
    await addUserGoodsService(goods.value)
    ElMessage.success("添加成功")
    visibleDrawer.value = false
    getGoodsList()
}
// 主图片上传成功的回调函数
const uploadSuccess = (result) => {
    goods.value.picture = result.data
    console.log(result.data);
}
// 详情图片上传成功的回调函数
const uploadSuccessTwo = (result) => {
    goods.value.pictures.push(result.data)
    console.log(goods.value.pictures);
}
//控制标题展示
const title = ref('')

//展示编辑弹窗
const showDialog = (row) => {
    visibleDrawer.value = true
    title.value = '编辑商品'
    //数据拷贝
    goods.value.name = row.name
    goods.value.categoryId = row.categoryId
    goods.value.desc = row.desc
    goods.value.price = row.price
    goods.value.picture = row.picture
    goods.value.status = row.status.toString()
    goods.value.id = row.id
}

const updateGoods= async () => {
    await updateGoodsService(goods.value)
    ElMessage.success("修改成功")
    getGoodsList()
    visibleDrawer.value = false
}

const deleteGoods = (row) => {
    ElMessageBox.confirm(
        '你确认删除该商品信息吗？',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            //用户点击了确认
            await deleteGoodsService(row.id)
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
            getGoodsList()
        })
        .catch(() => {
            //用户点击了取消
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}


const clearData = () => {
    goods.value.name = ""
    goods.value.categoryId = ""
    goods.value.desc = ""
    goods.value.price = ""
    goods.value.picture = ""
    goods.value.status = ""
}


</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>我的商品管理</span>
                <div class="extra">
                    <el-button type="primary" @click="visibleDrawer = true; title = '添加商品'; clearData()" >添加商品</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline>
            <el-form-item label="商品分类：">
                <el-select placeholder="请选择" v-model="categoryId" class="custom-form-item">
                    <el-option v-for="c in categorys" :key="c.id" :label="c.name" :value="c.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="商品状态：">
                <el-select placeholder="请选择" v-model="status" class="custom-form-item">
                    <el-option label="启用" value="1"></el-option>
                    <el-option label="禁用" value="0"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getGoodsList">搜索</el-button>
                <el-button @click="categoryId = ''; status = ''">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 商品列表 -->
        <el-table :data="goodsList" style="width: 100%">
            <el-table-column label="名称" prop="name"></el-table-column>
            <el-table-column label="分类" prop="categoryName" width="70" ></el-table-column>
            <el-table-column label="描述" prop="desc" width="300"> </el-table-column>
            <el-table-column label="价格" prop="price" width="70">
                <template v-slot="scope">
                    ¥ {{ scope.row.price }}
                </template>
            </el-table-column>
            <el-table-column label="图片" prop="picture">
                <template v-slot="scope">
                    <img :src="scope.row.picture" :alt="'图片' + scope.$index" style="width: 100px; height: 100px;">
                </template>
            </el-table-column>
            <el-table-column label="状态" prop="status" width="70" :formatter="formatStatus"></el-table-column>
            <el-table-column label="操作" width="100">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger"  @click="deleteGoods(row)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination :total="total" @current-change="pageChange" :page-size="pageSize" background
                layout="prev, pager, next" />
        </div>
        <!-- 抽屉 -->
        <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
            <!-- 添加商品表单 -->
            <el-form :model="goods" label-width="100px">
                <el-form-item label="商品名称">
                    <el-input v-model="goods.name" placeholder="请输入商品名称"></el-input>
                </el-form-item>
                <el-form-item label="商品分类">
                    <el-select placeholder="请选择" v-model="goods.categoryId">
                        <el-option v-for="c in categorys" :key="c.id" :label="c.name" :value="c.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品描述">
                    <el-input v-model="goods.desc" placeholder="请输入商品描述"></el-input>
                </el-form-item>
                <el-form-item label="商品价格">
                    <el-input v-model="goods.price" placeholder="请输入商品价格"></el-input>
                </el-form-item>
                <el-form-item label="商品封面">
                    <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false" action="/api/upload"
                        name="file" :on-success="uploadSuccess">
                        <img v-if="goods.picture" :src="goods.picture" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">+</el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="商品详情">
                    <div class="editor">
                        <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false" action="/api/upload"
                        name="file" :on-success="uploadSuccessTwo">
                        <img v-if="goods.pictures.length > 0" :src="goods.pictures[goods.pictures.length - 1]" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">+</el-icon>
                    </el-upload>
                    </div>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="goods.status">
                        <el-radio label="1">启用</el-radio>
                        <el-radio label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="title == '添加商品' ? addGoods() : updateGoods()">确认</el-button>
                    <el-button @click="visibleDrawer = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </el-card>
</template>
<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

/* 搜索框样式 */
.custom-form-item {
    /* 设置您需要的宽度、边距等样式 */
    width: 200px;
    /* 根据需要调整 */
    margin-right: 10px;
    /* 根据需要调整 */
}

/* 抽屉样式 */
.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}
</style>